package com.caishi.lkx.user.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ClientException;
import com.caishi.lkx.common.BaseApi;
import com.caishi.lkx.common.role.Roles;
import com.zzw.common.AliyunAuthPlugins;
import com.zzw.common.annotation.ResultIgnore;
import com.zzw.common.file.OssPlugins;
import com.zzw.common.file.OssPluginsAuto;
import com.zzw.common.util.HttpWebUtil;
import com.zzw.common.utils.ImageCode;
import com.zzw.common.utils.MD5Util;
import com.zzw.common.utils.TimeUtil;
import com.zzw.common.video.AliyunVideoPlugins;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.Collections;
import java.util.Locale;
import java.util.Map;

/**
 * @author by keray
 * date:2021/4/22 5:25 下午
 */
@Tag(name = "系统相关接口")
@RestController
@RequestMapping("/user/cu/sys/base")
public class SystemApi extends BaseApi {

//    @Resource
//    private DiamondHandler diamondHandler;

    @Autowired
    private AliyunAuthPlugins aliyunAuthPlugins;

    @Resource
    private AliyunVideoPlugins videoPlugins;


    @Operation(summary = "oss上传认证")
    @Parameters({
            @Parameter(name = "type", description = "oss类型 cdn|disk|middle cdn公共资源 disk归档资源 middle私密资源", required = true),
            @Parameter(name = "fileName", description = "文件名", required = true)
    })
    @Roles
    @GetMapping("/js-oss-up-auth")
    public Map<String, Object> upload(@RequestParam String type, @RequestParam String fileName) throws ClientException {
        OssPlugins ossPlugins = OssPluginsAuto.getOssPluginsByType(type);
        String ossFilePath = ossPlugins.getFilePath(fileName);
        AssumeRoleResponse assumeRoleResponse = aliyunAuthPlugins.stsAuth(Collections.singletonList("oss:*"), Collections.singletonList("acs:oss:*:*:*"), 3600L);
        return MapUtil.<String, Object>builder()
                .put("path", ossFilePath)
                .put("accessKeyId", assumeRoleResponse.getCredentials().getAccessKeyId())
                .put("accessKeySecret", assumeRoleResponse.getCredentials().getAccessKeySecret())
                .put("stsToken", assumeRoleResponse.getCredentials().getSecurityToken())
                .put("bucket", ossPlugins.ossConfig.getBucket())
                .put("endpoint", ossPlugins.ossConfig.getExtranetEndpoint())
                .put("region", ossPlugins.ossConfig.getRegion())
                .build();
    }

    @Operation(summary = "sts认证")
    @Roles
    @GetMapping("/js-auth-sts")
    public Map<String, Object> videoUpload(@RequestParam(defaultValue = "3600", required = false) Long timeout) throws Exception {
        AssumeRoleResponse assumeRoleResponse = aliyunAuthPlugins.stsAuth(Collections.singletonList("*"), Collections.singletonList("*"), timeout);
        return MapUtil.<String, Object>builder()
                .put("accessKeyId", assumeRoleResponse.getCredentials().getAccessKeyId())
                .put("accessKeySecret", assumeRoleResponse.getCredentials().getAccessKeySecret())
                .put("stsToken", assumeRoleResponse.getCredentials().getSecurityToken())
                .put("expiration", assumeRoleResponse.getCredentials().getExpiration())
                .put("timeout", timeout)
                .build();
    }


    @Operation(summary = "视频上传认证")
    @Parameters({
            @Parameter(name = "fileName", description = "文件名", required = true),
            @Parameter(name = "fileName", description = "视频名称", required = true),
    })
    @Roles
    @GetMapping("/js-video-up-auth")
    public Map<String, Object> videoUpload(@RequestParam String fileName, @RequestParam String title) throws Exception {
        return BeanUtil.beanToMap(videoPlugins.auth(fileName, title));
    }

    @Operation(summary = "oss读取认证 对于middle资源才会用到认证，资源需要通过认证才能读取")
    @Parameters({
            @Parameter(name = "type", description = "oss类型 cdn|disk|middle cdn公共资源 disk归档资源 middle私密资源", required = true),
    })
    @Roles
    @GetMapping("/js-oss-get-auth")
    public Map<String, Object> upload(@RequestParam String type) throws ClientException {
        OssPlugins ossPlugins = OssPluginsAuto.getOssPluginsByType(type);
        AssumeRoleResponse assumeRoleResponse = aliyunAuthPlugins.stsAuth(Arrays.asList("oss:PutObject", "oss:ListObjects"), Collections.singletonList("acs:oss:*:*:*"), 43200L);
        return MapUtil.<String, Object>builder()
                .put("accessKeyId", assumeRoleResponse.getCredentials().getAccessKeyId())
                .put("accessKeySecret", assumeRoleResponse.getCredentials().getAccessKeySecret())
                .put("stsToken", assumeRoleResponse.getCredentials().getSecurityToken())
                .put("bucket", ossPlugins.ossConfig.getExtranetEndpoint())
                .put("endpoint", ossPlugins.ossConfig.getEndpoint())
                .put("region", ossPlugins.ossConfig.getRegion())
                .build();
    }

    @GetMapping(value = "/valid-image", produces = MediaType.IMAGE_JPEG_VALUE)
    @Roles
    @ResultIgnore
    public BufferedImage getValidImage(HttpServletRequest request, HttpServletResponse response,
                                       @RequestParam(defaultValue = "255") Integer red,
                                       @RequestParam(defaultValue = "255") Integer green,
                                       @RequestParam(defaultValue = "255") Integer blue
    ) {

        response.setContentType("image/jpeg");
        String code = RandomUtil.randomString(4);
        HttpWebUtil.addCookie(response, "image-code", MD5Util.MD5Encode(code.toLowerCase(Locale.ROOT)));
        return ImageCode.image(code, red, green, blue);
    }

    @GetMapping(value = "/api-sign")
    @Roles
    public String apiSign() {
        return MD5Util.MD5Encode(userContext.currentTokenData().getDeviceUUID() + TimeUtil.DATE_TIME_FORMATTER_DAY.format(LocalDate.now()));
    }


    /**
     * 动态配置更新
     *
     * @param key   配置key
     * @param value 配置对象  对象类型使用
     * @param str   配置字符串  基本类型使用
     */
//    @PostMapping("/diamond/change")
//    @Roles
//    public void diamondChange(@RequestParam String key, @ModelAttribute("value") Object value, String str) {
//        diamondHandler.handler(key, value != null ? JSON.toJSONString(value) : str);
//    }
}
